class ElementRender {

    constructor(promptData, config, presetSize, presetRatio) {
        this.promptData = promptData;
        this.config = config;
        this.presetSize = presetSize;
        this.presetRatio = presetRatio;
        this.isOpen = false;
        // 渲染预设提示词分类
        this.renderPromptCategory = () => {
            const categoryContainer = document.createElement("div");
            categoryContainer.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_category_selector);
            this.promptData.forEach(item => {
                if (item.isNSFW && this.config.hiddenNSFW) {
                    return;
                }
                const tabButton = ElementCreator.createButton(item.name, {
                    onClick: e => {
                        // 获取所有 tabButton
                        const tabButtons = document.querySelectorAll(ElementSelector.zj_prompt_tab_button_selector);
                        // 去除之前的活动标签
                        tabButtons.forEach(t => {
                            t.classList.remove(PublicUtils.formateSelector(ElementSelector.zj_prompt_tab_button_active_selector));
                        })
                        // 标记当前标签为活动标签
                        e.target.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_tab_button_active_selector))

                        // 获取所有选项卡
                        const tabContents = document.querySelectorAll(ElementSelector.zj_prompt_tab_content_selector);
                        tabContents.forEach(t => {
                            if (t.getAttribute("data-tab") === e.target.getAttribute("data-tab")) {
                                t.style.display = 'flex';
                            } else {
                                t.style.display = 'none';
                            }
                        })
                    }
                }, PublicUtils.formateSelector(ElementSelector.zj_prompt_tab_button_selector));
                // 设置自定义属性
                tabButton.setAttribute(`data-tab`, `zj-prompt-tab-${item.name}`);
                categoryContainer.appendChild(tabButton);
            })
            // 设置默认活动选项
            categoryContainer.firstElementChild.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_tab_button_active_selector));
            return categoryContainer;
        }
        // 遍历数据
        this.traversePromptData = (dataArr, isFirstLoop = true) => {
            const div = document.createElement("div");
            const promptTagButtons = document.createElement("div");
            promptTagButtons.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_tags_selector));
            dataArr.forEach(item => {
                if (item["isNSFW"] && this.config["hiddenNSFW"]) {
                    return;
                }
                if (item["subData"] && Array.isArray(item["subData"])) {
                    const group = document.createElement("div");
                    if (isFirstLoop) {
                        // 设置自定义属性
                        group.setAttribute("data-tab", `zj-prompt-tab-${item.name}`);
                        group.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_tab_content_selector));
                        group.style.display = "none";
                        div.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_all_selector);
                    } else {
                        group.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_group_selector));
                    }
                    const groupTitle = document.createElement("div");
                    groupTitle.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_group_name_selector));
                    groupTitle.textContent = item.name;
                    group.appendChild(groupTitle);

                    const subData = this.traversePromptData(item["subData"], false);
                    subData.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_group_sub_data_selector));
                    group.appendChild(subData);
                    div.appendChild(group);
                } else {
                    const promptTag = ElementCreator.createButton(item.name, {
                        onClick: e => {
                            if (item["positivePrompt"]) {
                                const inputEl = PublicUtils.fillInPrompt("positive", item.positivePrompt);
                                ElementCreator.createSelectedPrompt("positive", item.name, item.positivePrompt);
                                PublicUtils.updateInputElement(inputEl);
                            }
                            if (item["negativePrompt"]) {
                                const inputEl = PublicUtils.fillInPrompt("negative", item.negativePrompt);
                                ElementCreator.createSelectedPrompt("negative", item.name, item.negativePrompt);
                                PublicUtils.updateInputElement(inputEl);
                            }
                        }, onRightClick: e => {

                        }
                    })
                    promptTagButtons.appendChild(promptTag);
                }
            })
            if (promptTagButtons.childElementCount !== 0) {
                div.appendChild(promptTagButtons);
            }
            return div;
        }
        // 渲染组
        this.renderPromptAll = () => {
            const promptAll = this.traversePromptData(this.promptData);
            promptAll.firstElementChild.style.display = 'flex';
            return promptAll;
        }
    }


    // 渲染预设提示词的
    renderPromptHelper() {
        const promptContainer = document.createElement("div");
        promptContainer.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_container_selector);

        const button = document.createElement("button");
        const text = document.createElement("span");
        text.textContent = "展开提示词";
        button.appendChild(text)
        const icon = document.createElement("span");
        icon.textContent = "▼";
        icon.classList.add("icon", "svelte-s1r2yt");
        button.appendChild(icon);
        button.addEventListener('click', () => {
            PublicUtils.switchHeightWithAnimation(promptContainer, {
                open: window.getComputedStyle(promptContainer).height === "51px",
                minHeight: 51,
                maxHeight: 700,
                borderWidth: 1,
                padding: 10
            })
            if (text.textContent === '展开提示词') {
                text.textContent = '收起提示词'
                anime({
                    targets: icon, rotate: 0, duration: 200, easing: 'easeOutQuad'
                })
            } else {
                text.textContent = '展开提示词';
                anime({
                    targets: icon, rotate: 90, duration: 200, easing: 'easeOutQuad'
                })
            }
        })
        button.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_unfold_or_fold_selector);

        promptContainer.appendChild(button);
        const category = this.renderPromptCategory();
        const promptAll = this.renderPromptAll();
        promptContainer.appendChild(category);
        promptContainer.appendChild(promptAll);

        const el = document.querySelector(ElementSelector.sys_txt2img_prompt_container_selector);
        el.appendChild(promptContainer);
    }

    // 渲染控制面板
    renderControlPanel() {
        // 创建一个控制面板容器元素
        const controlPanel = document.createElement("div");
        controlPanel.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_control_panel_selector);

        // 创建第一行
        const row1 = document.createElement("div");
        row1.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_control_panel_row_selector));

        // 创建自适应高度监听器，用于动态调整元素高度
        const promptPositiveSelectedAutoHeight = PublicUtils.autoAdjustHeightOnElementContentChange(ElementSelector.zj_prompt_selected_positive_selector, {});
        const promptNegativeSelectedAutoHeight = PublicUtils.autoAdjustHeightOnElementContentChange(ElementSelector.zj_prompt_selected_negative_selector, {});
        const promptPresetSizeAutoHeight = PublicUtils.autoAdjustHeightOnElementContentChange(ElementSelector.zj_prompt_preset_size_selector, {childChange: false});

        // 打开/关闭 提示词
        const switchButton = ElementCreator.createButton("打开提示词", {
            onClick: e => {
                if (this.isOpen) {
                    promptPositiveSelectedAutoHeight.stop();
                    promptNegativeSelectedAutoHeight.stop();
                    promptPresetSizeAutoHeight.stop();
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_container_selector, {open: false})
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_selected_positive_selector, {open: false});
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_selected_negative_selector, {open: false});
                    PublicUtils.switchHeightWithAnimation(controlPanel, {
                        open: false, minHeight: 73, borderWidth: 1, padding: 10
                    });
                    // 预设尺寸
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_preset_size_selector, {open: false})
                    switchButton.textContent = "打开提示词";
                    // 关闭提示词时重置展开收起选项
                    const unfoldOrFoldButton = document.querySelector(ElementSelector.zj_prompt_unfold_or_fold_selector);
                    unfoldOrFoldButton.firstElementChild.textContent = "展开提示词";
                    unfoldOrFoldButton.lastElementChild.style.transform = "rotate(90deg)";
                } else {
                    promptPositiveSelectedAutoHeight.start();
                    promptNegativeSelectedAutoHeight.start();
                    promptPresetSizeAutoHeight.start();
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_container_selector, {
                        open: true, maxHeight: 51, padding: 10, borderWidth: 1
                    })
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_selected_positive_selector, {open: true});
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_selected_negative_selector, {open: true});
                    PublicUtils.switchHeightWithAnimation(controlPanel, {
                        open: true, borderWidth: 1, padding: 10,
                    });
                    // 预设尺寸
                    PublicUtils.switchHeightWithAnimation(ElementSelector.zj_prompt_preset_size_selector, {
                        open: true, borderWidth: 1, padding: 10,
                    })
                    switchButton.textContent = "关闭提示词";
                }
                this.isOpen = !this.isOpen;
            }
        })
        switchButton.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_switch_selector);
        row1.appendChild(switchButton);
        // 重新加载按钮
        const reloadButton = ElementCreator.createButton("🔄️", {
            onClick: e => {

            }
        })
        reloadButton.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_reload_selector);
        row1.appendChild(reloadButton);
        controlPanel.appendChild(row1);

        const row2 = document.createElement("div");
        row2.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_control_panel_row_selector))
        // 清除正向提示词按钮
        const clearPositive = ElementCreator.createButton("清空正向提示词", {
            onClick: e => {
                const positiveInput = document.querySelector(ElementSelector.sys_txt2img_prompt_positive_selector);
                positiveInput.value = '';
                document.querySelector(ElementSelector.zj_prompt_selected_positive_selector).lastElementChild.innerHTML = '';
                PublicUtils.updateInputElement(positiveInput);
            }
        });
        clearPositive.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_clear_positive_selector);
        row2.appendChild(clearPositive);
        controlPanel.appendChild(row2);

        const row3 = document.createElement("div");
        row3.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_control_panel_row_selector))
        // 清除反向提示词按钮
        const clearNegative = ElementCreator.createButton("清空反向提示词", {
            onClick: e => {
                const negativeInput = document.querySelector(ElementSelector.sys_txt2img_prompt_negative_selector);
                negativeInput.value = '';
                document.querySelector(ElementSelector.zj_prompt_selected_negative_selector).lastElementChild.innerHTML = '';
                PublicUtils.updateInputElement(negativeInput);
            }
        });
        clearNegative.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_clear_negative_selector);
        row3.appendChild(clearNegative);
        controlPanel.appendChild(row3);

        const row4 = document.createElement("div");
        row4.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_control_panel_row_selector))
        // 清除所有提示词按钮
        const clearAll = ElementCreator.createButton("清空所有提示词", {
            onClick: e => {
                const positiveInput = document.querySelector(ElementSelector.sys_txt2img_prompt_positive_selector);
                positiveInput.value = '';
                document.querySelector(ElementSelector.zj_prompt_selected_positive_selector).lastElementChild.innerHTML = '';
                const negativeInput = document.querySelector(ElementSelector.sys_txt2img_prompt_negative_selector);
                negativeInput.value = '';
                document.querySelector(ElementSelector.zj_prompt_selected_negative_selector).lastElementChild.innerHTML = '';
                PublicUtils.updateInputElement(positiveInput, negativeInput);
            }
        });
        clearAll.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_clear_all_selector);
        row4.appendChild(clearAll);
        controlPanel.appendChild(row4);

        const el = document.querySelector(ElementSelector.sys_txt2img_actions_column_selector);
        el.appendChild(controlPanel);
    }

    // 渲染已选择提示词
    renderSelectedPromptHelper() {
        ElementCreator.createSelectedPromptContainer("positive");
        ElementCreator.createSelectedPromptContainer("negative");
    }

    // 渲染预设尺寸
    renderPresetSizeHelper() {
        const presetSizeContainer = document.createElement("div");
        presetSizeContainer.id = PublicUtils.formateSelector(ElementSelector.zj_prompt_preset_size_selector);
        this.presetSize.forEach(item => {
            /// TODO
            const sizeButton = ElementCreator.createButton(`${item.name}(${item.width} x ${item.height})`, {
                onClick: e => {
                    const imgWidth = document.querySelector(ElementSelector.sys_txt2img_width_selector);
                    const imgHeight = document.querySelector(ElementSelector.sys_txt2img_height_selector);
                    imgWidth.value = item.width;
                    imgHeight.value = item.height;
                    PublicUtils.updateInputElement(imgWidth, imgHeight);
                }
            })
            sizeButton.classList.add(PublicUtils.formateSelector(ElementSelector.zj_prompt_preset_size_button_selector));
            presetSizeContainer.appendChild(sizeButton);
        })
        document.querySelector("#component-87").insertAdjacentElement("beforebegin", presetSizeContainer);
    }

    // 渲染保存当前参数到提示词
    renderSaveImgInfoHelper() {
        Txt2ImgInfoHelper.execute();
    }
}